<?php
/**
 * Created by PhpStorm.
 * User: John
 * Date: 16-12-30
 * Time: 下午4:03
 */
namespace app\backend\model;

use think\Model;

class Trust extends Model
{
    private $ruleTable    = 'z_settle_rule';
    private $settleTable  = 'z_settle_order';
    private $buildingTable = 'z_building';
    private $houseTable    = 'z_house';
    private $memberTable   = 'z_member';
    public function __construct() {
        parent::__construct();
    }

    /**
     * 增加房源的分成比例规则
     * @date   2017-1-22
     * @author wuhao
     *
     * @param  int  $settleNum   托管订单号
     * @param  int  $rentalRate  出租率
     * @param  int  $sharingRate 分成率
     * @param  int  $ownerId     业主id
     * @param  int  $trustId     托管id
     *
     * @return
     */
    public function addShareRule($settleNum, $rentalRate, $sharingRate, $ownerId, $trustId)
    {
        $data = [
            'settlenum'    => $settleNum,
            'rental_rate'  => $rentalRate,
            'split_ratio'  => $sharingRate,
            'owner_id'     => $ownerId,
            'trust_id'     => $trustId,
        ];
        $res =  $this->setTable($this->ruleTable)->insertGetId($data);
        return $res;
    }

    /**
     * 判断用户是否有权限修改托管规则
     * @date   2017-1-22
     * @author wuhao
     *
     * @param  int     $settleNum   托管订单号
     * @param  int     $trustId     托管id
     * @param  string  $type        rule 或 order
     *
     * @return
     */
    public function checkAuth($settleNum, $trustId, $type = 'rule')
    {
        if ($type == 'rule') {
            $where = ['settlenum' => $settleNum, 'trust_id' => $trustId];
            return $this->setTable($this->ruleTable)->where($where)->find();
        } else {
            $where = ['orderid' => $settleNum, 'trust_id' => $trustId];
            return $this->setTable($this->settleTable)->where($where)->find();
        }
    }

    /**
     * 检查是否已有房源的分成比例规则
     * @date   2017-1-22
     * @author wuhao
     *
     * @param  int  $settleNum   托管订单号
     * @param  int  $rentalRate  出租率
     * @param  int  $ownerId     业主id
     * @param  int  $trustId    托管id
     *
     * @return
     */
    public function checkShareRule($settleNum, $rentalRate, $ownerId, $trustId)
    {
        $where = [
            'settlenum'   => $settleNum,
            'rental_rate' => $rentalRate,
            'owner_id'    => $ownerId,
            'trust_id'    => $trustId
        ];

        $res = $this->setTable($this->ruleTable)->where($where)->find();
        return $res;
    }

    /**
     * 编辑/添加房源的分成比例规则
     * @date   2017-1-23
     * @author wuhao
     *
     * @param  int    $settleNum   托管订单号
     * @param  int    $ownerId     业主ID
     * @param  array  $rateArr     分成比例规则数组
     * @param  int    $trustId     托管公司id
     *
     * @return
     */
    public function setSharingRule($settleNum, $ownerId, $rateArr, $trustId)
    {
        $where = [
            'settlenum' => $settleNum,
            'trust_id'  => $trustId,
        ];
        //先删除相关数据
        $res = $this->setTable($this->ruleTable)->where($where)->delete();
        if ($res) {
            //再加入新的数据
            $status = 1;
            foreach ($rateArr as $rate) {
                $data = [
                    'owner_id'    => $ownerId,
                    'settlenum'   => $settleNum,
                    'rental_rate' => $rate['rental'],
                    'split_ratio' => $rate['split'],
                    'trust_id'    => $trustId,
                ];
                $tmp = $this->setTable($this->ruleTable)->insertGetId($data);
                if (!$tmp) {
                    $status = 0;
                    zft_log('trust/set_sharing_rule_fail', $this->getLastSql());
                }
            }
            if ($status == 1) {
                return ['code'=>200];
            } else {
                return ['code'=>201];
            }
        } else {
            //没删成功
            zft_log('trust/set_sharing_rule_fail', $this->getLastSql());
            return ['code'=>202];
        }
    }

    /**
     * 生成托管订单
     * @date   2017-1-22
     * @author wuhao
     *
     * @param  int    $buildingId  楼宇ID
     * @param  int    $ownerId     业主id
     * @param  int    $trustId     托管公司id
     * @param  int    $settleType  结算类型 1=年 2=月
     * @param  int    $dozenMoney  保底金额
     * @param  int    $billingDay  账单日
     * @param  int    $beginTime   托管起始时间
     * @param  int    $endTime     托管结束时间
     * @param  int    $settleNum   托管账单号
     * @return
     */
    public function addSettleOrder($buildingId, $ownerId, $trustId, $settleType, $dozenMoney, $billingDay, $beginTime, $endTime, $cycleMark, $settleNum)
    {
        $data = [
            'owner_id'     => $ownerId,
            'building_id'  => $buildingId,
            //'house_ids'    => $houseId,
            'settle_type'  => $settleType,
            'dozen_money'  => fen($dozenMoney),
            'billing_date' => $billingDay,
            'begintime'    => $beginTime,
            'endtime'      => $endTime,
            'tax'          => 0,
            'ordertime'    => time(),
            'cycle_mark'   => $cycleMark,
            'trust_id'     => $trustId,
            'orderid'      => $settleNum,
            //'mobile'       => $mobile,
        ];

        return $this->setTable($this->settleTable)->insertGetId($data);
    }

    /**
     * 根据业主，楼栋获取对应的托管订单信息
     * @date   2017-1-22
     * @author wuhao
     *
     * @param  int  $buildId  楼栋
     * @param  int  $trustId  托管公司id
     * @param  int  $ownerId  业主id
     *
     * @return array
     */
    public function getSettleOrder($ownerId, $trustId, $buildId)
    {
        $where = [
            'owner_id'    => $ownerId,
            'building_id' => $buildId,
            'trust_id'    => $trustId,
            'status'      => 1,
        ];
        return $this->setTable($this->settleTable)->where($where)->select();
    }


    /**
     * 编辑托管订单信息
     * @date   2017-1-23
     * @author wuhao
     *
     * @param  string $settleNum   托管订单号
     * @param  int    $settleType  结算类型 1=年 2=月
     * @param  int    $dozenMoney  保底金额
     * @param  int    $billingDay  账单日
     * @param  int    $beginTime   托管起始时间
     * @param  int    $endTime     托管结束时间
     * @param  int    $cycleMark   结算标记
     *
     * @return
     */
    public function setSettleOrder($settleNum, $settleType, $dozenMoney, $billingDay, $beginTime, $endTime, $cycleMark)
    {
        $where['orderid'] = $settleNum;
        $data = [
            'settle_type'  => $settleType,
            'dozen_money'  => $dozenMoney,
            'billing_date' => $billingDay,
            'begintime'    => strtotime($beginTime),
            'endtime'      => strtotime($endTime),
            'ordertime'    => time(),
            'cycle_mark'   => $cycleMark,
        ];
        return $this->setTable($this->settleTable)->where($where)->update($data);
    }

    /**
     * 获取托管结算规则数据
     * @date   2017-01-19
     * @author Lanlc
     *
     * @param  array   $where  查询条件
     * @param  string  $field  查询字段
     *
     * @return
     */
    public function getTrust($where, $field, $offSet=0, $pageSize=500)
    {
        return $this->setTable($this->settleTable)->field($field)->where($where)->limit($offSet, $pageSize)->select();
    }

    /**
     * 根据楼宇id获取对应的托管信息
     * @date   2017-01-19
     * @author wuhao
     *
     * @param  int  $buildingId   楼宇ID
     *
     * @return array
     */
    public function getTrustInfoByBuildingId($buildingId)
    {
        $where['building_id'] = $buildingId;
        $where['status'] = 1;
        $res = $this->setTable($this->settleTable)->where($where)->find();
        return $res;
    }

    /**
     * 根据托管订单获取对应的托管起始时间
     * @date   2017-01-22
     * @author wuhao
     *
     * @param  int  $settleNum   托管订单号
     *
     * @return
     */
    public function getTrustBeginTime($settleNum)
    {
        return $this->setTable($this->settleTable)->where(['orderid'=>$settleNum])->field('begintime')->find();
    }

    /**
     * 获取我的合同详细信息
     * @date   2017-01-23
     * @author wuhao
     *
     * @param int  $settleNum  订单号
     * @return
     */
    public function getOrderDetail($settleNum)
    {
        $where = [
            'orderid'   => $settleNum,
            //'trust_id'  => $trustId,
        ];
        $field = 'owner_id, orderid, trust_id, building_id,dozen_money, settle_type, begintime, endtime, billing_date';
        return $this->setTable($this->settleTable)->field($field)->where($where)->find();
    }
    /**
     * 获取我的合同详细信息
     * @date   2017-01-23
     * @author wuhao
     *
     * @param int  $settleNum  订单号
     * @return
     */
    public function getRuleDetail($settleNum)
    {
        $where = [
            'settlenum' => $settleNum,
            //'trust_id'  => $trustId,
        ];
        $field = 'rental_rate, split_ratio';
        return $this->setTable($this->ruleTable)->field($field)->where($where)->select();
    }

    /**
     * 更新托管订单表数据
     * @date   2017-01-23
     * @author Lanlc
     *
     * @param  array  $where  更新条件
     * @param  array  $data   更新数据
     *
     * @return
     */
    public function updateTrustOrder($where, $data)
    {
        $this->setTable($this->settleTable)->where($where)->update($data);
    }

    /**
     * 获取我的合同
     * @date   2017-01-18
     * @author wuhao
     *
     * @param  int  $memberId  用户ID
     * @param  int  $dtype     用户类型
     * @param  int  $page      页数
     * @param int   $pageSize  每页个数
     *
     * @return array
     */
    public function getMyOrder($memberId, $dtype, $page, $pageSize = 3)
    {
        if ($dtype === 0) {//管理员查询所有
            $where = [];
        } elseif (in_array($dtype, [4, 3])) {
            //托管运营
            $where = ['s.trust_id' => $memberId];
        } else {
            //业主
            $where = ['s.owner_id' => $memberId];
        }

        $join = [
            [$this->buildingTable. ' b', 's.building_id=b.id', 'LEFT'],
            [$this->memberTable. ' m', 's.owner_id=m.id', 'LEFT'],
        ];

        $field = 's.orderid, s.owner_id, s.trust_id, s.building_id, b.province, b.city, b.country, b.name, b.address, s.begintime, s.endtime, m.nickname, m.mobile';
        $res = $this->setTable($this->settleTable . ' s')->field($field)->join($join)->where($where)->where('s.status = 1')->page($page, $pageSize)->select();
        if (!$res) {
            return [];
        }
        $sum = $this->setTable($this->settleTable . ' s')->join($join)->where($where)->where('s.status = 1')->count();
        $data  = [
            'list'         => $res,
            'current_page' => $page,
            'total'        => ceil($sum / $pageSize),
        ];
        return $data;
    }

    /**
     * 获取托管订单信息
     * @date   2017-03-16
     * @author wuhao
     *
     * @param  array   $where  条件
     * @param  string  $field  字段
     *
     * @return
     */
    public function getTrustedInfo($where, $field = '*')
    {
        return $this->setTable($this->settleTable)->field($field)->where($where)->select();
    }

    /**
     * 使合约失效
     * @date   2017-4-5
     * @author wuhao
     *
     * @param  string  $ordernum    合同编号
     * @param  int     $status      合约状态 1=生效 0=失效
     *
     * @return
     */
    public function forbidTrust($ordernum, $status)
    {
        if (!$ordernum || !in_array($status, [0, 1])) {
            return false;
        }
        $data  = ['status' => $status];
        $where = ['orderid' => $ordernum];
        return $this->setTable($this->settleTable)->where($where)->update($data);
    }

    /**
     * 根据业主id,楼宇id 获取托管表里的托管方的id
     * @date   2016-02-9
     * @author banjin
     * @param  $mid        int  业主id
     * @param  $buildingId int  楼宇id
     *
     * @return
     */
    public function getTrustId($mid, $buildingId)
    {
        if (!$mid ||!$buildingId) {
            return false;
        }
        $where = [
            'owner_id' => $mid,
            'building_id' => $buildingId,
        ];
        $res = $this->table($this->settleTable)->where($where)->field('trust_id')->find();
        return $res;
    }
}
